package com.example.myspringbootpj.controller;

import com.example.myspringbootpj.entity.User;
import com.example.myspringbootpj.mapper.UserMapper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class userInFor {

    private static final String FIXED_FILE_PATH = "D:" + File.separator + "fgobb" + File.separator + "uploaded_images";



    private final UserMapper userMapper;
    @Autowired
    public userInFor(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    //用户信息显示
    @GetMapping("/userInFo")
    public Map<String, Object> getUserInFor(HttpSession session) {

        String userID = (String) session.getAttribute("userID");

        // 根据用户 ID 查询用户信息
User user = userMapper.selectUserById(userID);
//return user;
// 创建一个 Map，包含 userID 和用户信息
        Map<String, Object> response = new HashMap<>();
        response.put("userID", userID);
        response.put("user", user);

        return response;


//        return userMapper.selectUserById(userID); // 返回单个用户信息

    }

    //修改用户名
    @PutMapping("/upUserName")
    public String upUserName(
                         @RequestParam("user_name")String userName,HttpSession session) {

        String userID = (String) session.getAttribute("userID");

// 检查用户是否已登录
        if (userID == null) {
            return "用户未登录！"; // 提示用户未登录
        }

        int userNID = userMapper.updateNaById(userID, userName);

        if (userNID > 0) {
            return "成功";
        }else {
            return "失败了！";
        }

    }

    //更改头像
    @PutMapping("/upUserImage")
    public ResponseEntity<String> updateUserImage(
            @RequestParam("user_image") MultipartFile userImage,
            HttpSession session) {

        // 获取当前用户ID
        String userID = (String) session.getAttribute("userID");

        if (userID == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户未登录！");
        }

        // 检查文件是否为空
        if (userImage == null || userImage.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("文件为空，无法上传！");
        }

        try {
            // 保存文件
            String savedFilePath = saveFile(userImage, FIXED_FILE_PATH);

            // 更新数据库中用户头像路径
            int rowsUpdated = userMapper.updateImById(userID, savedFilePath);

            if (rowsUpdated > 0) {
                return ResponseEntity.ok("头像更新成功！");
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("更新失败，数据库操作失败！");
            }

        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("头像更新失败，文件保存错误！");
        }
    }

    // 保存文件
    private String saveFile(MultipartFile userImage, String path) throws IOException {
        File dir = new File(path);

        // 创建目录（如果不存在）
        if (!dir.exists() && !dir.mkdirs()) {
            throw new IOException("无法创建目录：" + path);
        }

        // 文件名确保唯一性，防止覆盖
        String fileName = System.currentTimeMillis() + "_" + userImage.getOriginalFilename();
        File file = new File(dir, fileName);

        // 保存文件
        userImage.transferTo(file);

        return file.getAbsolutePath();
    }


    //更改密码
    @PutMapping("/upUserPW")
    public String upUserPW(
            @RequestParam("user_password")String userPaWo,HttpSession session) {

        String userID = (String) session.getAttribute("userID");

// 检查用户是否已登录
        if (userID == null) {
            return "用户未登录！"; // 提示用户未登录
        }

        int userNID = userMapper.updatePsById(userID, userPaWo);

        if (userNID > 0) {
            return "成功了✌";
        }else {
            return "失败了";
        }

    }

}
